package com.ax.framework.jfinal.directive

import cn.hutool.core.io.resource.ClassPathResource
import cn.hutool.core.util.ReflectUtil
import com.jfinal.template.Directive
import com.jfinal.template.Env
import com.jfinal.template.io.FastStringWriter
import com.jfinal.template.io.Writer
import com.jfinal.template.stat.Scope


class FileToStrDirective : Directive() {
    override fun exec(env: Env, scope: Scope, writer: Writer) {
        //获取指令之前有多少空格
        val fast_string_writer = ReflectUtil.getFieldValue(writer, "out") as FastStringWriter
        val buffer = fast_string_writer.buffer
        val last_index_of = buffer.lastIndexOf("\r\n")
        val substring = buffer.substring(last_index_of + 2)

        //传入指令的参数列表
        val directory_params = exprList.exprArray
        val file_path = directory_params[0]

        //从classpath 加载文件, classpath相对路径会很烦, 所以, 传相对根目录的路径好了
        var string = ClassPathResource(file_path.toString()).readUtf8Str()

        var split = string.split("\r\n")
        if (split.size == 1) {
            split = string.split("\n")
        }

        split.forEachIndexed { idx, str ->
            //if (idx == 0) write(writer, str)else
            write(writer, "\r\n");
            write(writer, substring);
            write(writer, str)
        }
    }
}